import logging
from django.db.models import Q
from django.utils import timezone
from django.shortcuts import get_object_or_404

from rest_framework import status, viewsets, mixins, filters, parsers
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.decorators import action
from django_filters.rest_framework import DjangoFilterBackend

from drf_spectacular.utils import extend_schema, OpenApiParameter, OpenApiExample
from drf_spectacular.types import OpenApiTypes

from .models import Vehicle
from .serializers import (
    VehicleSerializer, VehicleCreateSerializer, VehicleUpdateSerializer,
    VehicleLocationUpdateSerializer, VehicleListSerializer
)
from .permissions import IsVehicleOwnerOrReadOnly
from user_app.utils import TencentCOSManager
from user_app.models import User

logger = logging.getLogger(__name__)


class VehicleViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """车辆视图集"""
    
    queryset = Vehicle.objects.all()
    serializer_class = VehicleSerializer
    permission_classes = [IsVehicleOwnerOrReadOnly]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['status', 'vehicle_type', 'is_approved']
    search_fields = ['license_plate', 'current_location']
    ordering_fields = ['created_at', 'capacity', 'available_time']
    ordering = ['-created_at']
    
    def get_serializer_class(self):
        """根据操作选择序列化器"""
        if self.action == 'create_or_update':
            return VehicleCreateSerializer
        elif self.action == 'list':
            return VehicleListSerializer
        elif self.action == 'retrieve':
            return VehicleSerializer
        return self.serializer_class
    
    def get_permissions(self):
        """根据操作选择权限"""
        if self.action == 'list' or self.action == 'retrieve':
            return [AllowAny()]
        return super().get_permissions()
    
    def get_queryset(self):
        """获取查询集"""
        queryset = super().get_queryset()
        
        # 检查是否需要返回当前用户车辆
        personal = self.request.query_params.get('personal', '').lower() == 'true'
        if personal and self.request.user.is_authenticated:
            queryset = queryset.filter(user=self.request.user)
        
        # 如果是获取我的车辆列表，则只返回当前用户的车辆
        if self.action == 'my_vehicles':
            return queryset.filter(user=self.request.user)
        
        # 如果是搜索附近的车辆，则根据经纬度进行筛选
        if self.action == 'nearby':
            longitude = self.request.query_params.get('longitude')
            latitude = self.request.query_params.get('latitude')
            distance = self.request.query_params.get('distance', 50)  # 默认50公里
            
            if longitude and latitude:
                # 这里简化处理，实际项目中应该使用地理位置查询
                # 例如使用Django的GeoDjango或者自定义SQL查询
                # 这里仅作为示例，返回所有车辆
                return queryset
        
        # 修改：不再默认只返回空闲状态的车辆，而是返回所有车辆
        # 如果需要筛选特定状态，可以通过status参数进行筛选
        # if self.action == 'list' and not self.request.query_params.get('status'):
        #     return queryset.filter(status=Vehicle.Status.AVAILABLE)
        
        return queryset
    
    @extend_schema(
        summary="获取车辆列表",
        description="""获取车辆列表，支持按状态和车辆类型筛选，以及搜索和排序。
        
        默认返回所有车辆，可以通过status参数筛选特定状态的车辆。
        可以通过is_approved参数筛选已审核/未审核的车辆。
        可以通过search参数搜索车牌号或当前位置。
        可以通过ordering参数指定排序字段，如created_at、capacity等。
        is_approved字段表示车辆是否已通过审核
        """,
        parameters=[
            OpenApiParameter(
                name='status',
                description='车辆状态',
                type=str,
                enum=['available', 'in_transit', 'maintenance', 'unavailable']
            ),
            OpenApiParameter(
                name='vehicle_type',
                description='车辆类型',
                type=str,
                enum=['tank_truck', 'flat_bed', 'box_truck', 'other']
            ),
            OpenApiParameter(
                name='is_approved',
                description='审核状态 (true: 已审核通过, false: 未审核或审核未通过)',
                type=bool
            ),
            OpenApiParameter(
                name='search',
                description='搜索关键词（车牌号或当前位置）',
                type=str
            ),
            OpenApiParameter(
                name='ordering',
                description='排序字段（如created_at、capacity等）',
                type=str
            ),
            OpenApiParameter(
                name='personal',
                description='是否只返回当前用户车辆',
                type=bool
            ),
        ],
        responses={
            200: VehicleListSerializer(many=True)
        },
        tags=['Vehicles'],
        examples=[
            OpenApiExample(
                '车辆列表响应示例',
                summary='车辆列表响应示例',
                description='返回车辆列表的示例数据',
                value=[
                    {
                        "id": 1,
                        "user_name": "13800138000",
                        "license_plate": "粤A12345",
                        "vehicle_type": "tank_truck",
                        "vehicle_type_display": "罐车",
                        "capacity": "20.00",
                        "current_location": "广东省广州市天河区",
                        "status": "available",
                        "status_display": "空闲",
                        "available_time": "2025-10-25T08:00:00Z",
                        "is_approved": True,
                        "created_at": "2025-10-20T10:00:00Z"
                    }
                ]
            )
        ]
    )
    def list(self, request, *args, **kwargs):
        """获取车辆列表"""
        return super().list(request, *args, **kwargs)
    
    @extend_schema(
        summary="获取车辆详情",
        description="""根据车辆ID获取车辆的详细信息，包括车辆图片等。
        
        特殊说明：
        - 当ID为'me'时，返回当前司机用户的第一辆车辆信息
        - 当ID为具体数字时，返回对应ID的车辆信息
        - is_approved字段表示车辆是否已通过审核 (true: 已审核通过, false: 未审核或审核未通过)
        - longitude和latitude字段表示车辆最后报告的经纬度位置信息
        """,
        responses={
            200: VehicleSerializer
        },
        tags=['Vehicles'],
        examples=[
            OpenApiExample(
                '车辆详情响应示例',
                summary='车辆详情响应示例',
                description='返回车辆详细信息的示例数据',
                value={
                    "id": 1,
                    "user": {
                        "id": 1,
                        "phone": "13800138000",
                        "role": "driver",
                        "avatar": "https://example.com/avatar.jpg",
                        "company": "ABC运输公司",
                        "credit_score": "4.8"
                    },
                    "license_plate": "粤A12345",
                    "vehicle_type": "tank_truck",
                    "vehicle_type_display": "罐车",
                    "capacity": "20.00",
                    "length": "12.50",
                    "width": "2.50",
                    "height": "3.00",
                    "current_location": "广东省广州市天河区",
                    "longitude": "113.280661",
                    "latitude": "23.125178",
                    "location_updated_at": "2025-10-21T10:00:00Z",
                    "status": "available",
                    "status_display": "空闲",
                    "available_time": "2025-10-25T08:00:00Z",
                    "vehicle_license": "LD123456789012",
                    "vehicle_license_image": "https://example.com/license.jpg",
                    "is_approved": True,
                    "images": [
                        {
                            "id": 1,
                            "image_url": "https://example.com/vehicle_front.jpg",
                            "description": "车辆正面",
                            "image_type": "exterior",
                            "image_type_display": "车辆外观",
                            "created_at": "2025-10-20T10:00:00Z"
                        }
                    ],
                    "created_at": "2025-10-20T10:00:00Z",
                    "updated_at": "2025-10-21T10:00:00Z"
                }
            )
        ]
    )
    def retrieve(self, request, *args, **kwargs):
        """获取车辆详情"""
        # 检查是否使用了'me'参数
        if self.kwargs.get('pk') == 'me':
            # 检查用户是否已认证
            if not request.user.is_authenticated:
                return Response(
                    {'error': '用户未认证'}, 
                    status=status.HTTP_401_UNAUTHORIZED
                )
            
            # 检查用户是否为司机角色
            if request.user.role != User.Role.DRIVER:
                return Response(
                    {'error': '只有司机用户才能使用此功能'}, 
                    status=status.HTTP_403_FORBIDDEN
                )
            
            # 获取当前司机的第一辆车辆
            try:
                vehicle = Vehicle.objects.filter(user=request.user).first()
                if not vehicle:
                    return Response(
                        {'error': '当前用户没有注册车辆'}, 
                        status=status.HTTP_404_NOT_FOUND
                    )
                
                serializer = self.get_serializer(vehicle)
                return Response(serializer.data)
            except Exception as e:
                return Response(
                    {'error': '获取车辆信息失败'}, 
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR
                )
        
        # 处理正常的ID查询
        return super().retrieve(request, *args, **kwargs)
    
    @extend_schema(
        summary="创建或更新车辆信息",
        description="""创建新车辆或更新现有车辆信息。
        
        如果指定车牌号的车辆已存在，则更新该车辆信息；否则创建新车辆。
        支持同时上传车辆图片信息。
        is_approved字段表示车辆是否已通过审核，该字段由管理员在审核过程中设置，用户无法直接修改。
        (true: 已审核通过, false: 未审核或审核未通过)
        
        注意事项：
        - 只有认证的司机用户才能调用此接口
        - 可以通过images参数传递图片URL或直接上传图片文件
        - 如果上传图片文件，系统会自动将其存储到腾讯云COS并生成访问URL
        - longitude和latitude字段用于记录车辆的当前位置经纬度信息
        """,
        request={
            'multipart/form-data': {
                'type': 'object',
                'properties': {
                    'license_plate': {
                        'type': 'string',
                        'description': '车牌号'
                    },
                    'vehicle_type': {
                        'type': 'string',
                        'enum': ['tank_truck', 'flat_bed', 'box_truck', 'other'],
                        'description': '车辆类型'
                    },
                    'capacity': {
                        'type': 'number',
                        'description': '载重量(吨)'
                    },
                    'length': {
                        'type': 'number',
                        'description': '车长(米)'
                    },
                    'width': {
                        'type': 'number',
                        'description': '车宽(米)'
                    },
                    'height': {
                        'type': 'number',
                        'description': '车高(米)'
                    },
                    'current_location': {
                        'type': 'string',
                        'description': '当前位置'
                    },
                    'longitude': {
                        'type': 'number',
                        'description': '经度'
                    },
                    'latitude': {
                        'type': 'number',
                        'description': '纬度'
                    },
                    'status': {
                        'type': 'string',
                        'enum': ['available', 'in_transit', 'maintenance', 'unavailable'],
                        'description': '状态'
                    },
                    'available_time': {
                        'type': 'string',
                        'format': 'date-time',
                        'description': '可用时间'
                    },
                    'vehicle_license': {
                        'type': 'string',
                        'description': '行驶证号'
                    },
                    'vehicle_license_image': {
                        'type': 'string',
                        'format': 'binary',
                        'description': '行驶证照片'
                    },
                    'vehicle_image': {
                        'type': 'string',
                        'format': 'binary',
                        'description': '车辆图片'
                    },
                    'image': {
                        'type': 'string',
                        'format': 'binary',
                        'description': '车辆图片（只允许上传一张图片）'
                    }
                }
            }
        },
        responses={
            200: OpenApiTypes.OBJECT,
            201: OpenApiTypes.OBJECT
        },
        tags=['Vehicles'],
        examples=[
            OpenApiExample(
                '创建车辆请求示例',
                summary='创建车辆请求示例',
                description='创建车辆的请求参数示例',
                value={
                    "license_plate": "粤A12345",
                    "vehicle_type": "tank_truck",
                    "capacity": "20.00",
                    "length": "12.50",
                    "width": "2.50",
                    "height": "3.00",
                    "current_location": "广东省广州市天河区",
                    "longitude": "113.280661",
                    "latitude": "23.125178",
                    "status": "available",
                    "available_time": "2025-10-25T08:00:00Z",
                    "vehicle_license": "LD123456789012",
                    "vehicle_license_image": "https://example.com/license.jpg",
                    "vehicle_image": "https://example.com/vehicle.jpg",
                    "image": ""
                }
            ),
            OpenApiExample(
                '创建车辆响应示例',
                summary='创建车辆响应示例',
                description='创建车辆成功的响应示例',
                value={
                    "message": "车辆信息创建成功",
                    "vehicle": {
                        "id": 1,
                        "user": {
                            "id": 1,
                            "phone": "13800138000",
                            "role": "driver",
                            "avatar": "https://example.com/avatar.jpg",
                            "company": "ABC运输公司",
                            "credit_score": "4.8"
                        },
                        "license_plate": "粤A12345",
                        "vehicle_type": "tank_truck",
                        "vehicle_type_display": "罐车",
                        "capacity": "20.00",
                        "length": "12.50",
                        "width": "2.50",
                        "height": "3.00",
                        "current_location": "广东省广州市天河区",
                        "longitude": "113.280661",
                        "latitude": "23.125178",
                        "location_updated_at": "2025-10-21T10:00:00Z",
                        "status": "available",
                        "status_display": "空闲",
                        "available_time": "2025-10-25T08:00:00Z",
                        "vehicle_license": "LD123456789012",
                        "vehicle_license_image": "https://example.com/license.jpg",
                        "vehicle_image": "https://example.com/vehicle.jpg",
                        "is_approved": False,
                        "images": [
                            {
                                "id": 1,
                                "image_url": "https://example.com/vehicle_front.jpg",
                                "description": "车辆正面",
                                "image_type": "exterior",
                                "image_type_display": "车辆外观",
                                "created_at": "2025-10-20T10:00:00Z"
                            }
                        ],
                        "created_at": "2025-10-20T10:00:00Z",
                        "updated_at": "2025-10-21T10:00:00Z"
                    }
                }
            ),
            OpenApiExample(
                '更新车辆响应示例',
                summary='更新车辆响应示例',
                description='更新车辆成功的响应示例',
                value={
                    "message": "车辆信息更新成功",
                    "vehicle": {
                        "id": 1,
                        "user": {
                            "id": 1,
                            "phone": "13800138000",
                            "role": "driver",
                            "avatar": "https://example.com/avatar.jpg",
                            "company": "ABC运输公司",
                            "credit_score": "4.8"
                        },
                        "license_plate": "粤A12345",
                        "vehicle_type": "tank_truck",
                        "vehicle_type_display": "罐车",
                        "capacity": "20.00",
                        "length": "12.50",
                        "width": "2.50",
                        "height": "3.00",
                        "current_location": "广东省广州市天河区",
                        "longitude": "113.280661",
                        "latitude": "23.125178",
                        "location_updated_at": "2025-10-21T10:00:00Z",
                        "status": "available",
                        "status_display": "空闲",
                        "available_time": "2025-10-25T08:00:00Z",
                        "vehicle_license": "LD123456789012",
                        "vehicle_license_image": "https://example.com/license.jpg",
                        "vehicle_image": "https://example.com/vehicle.jpg",
                        "is_approved": False,
                        "images": [
                            {
                                "id": 1,
                                "image_url": "https://example.com/vehicle_front.jpg",
                                "description": "车辆正面",
                                "image_type": "exterior",
                                "image_type_display": "车辆外观",
                                "created_at": "2025-10-20T10:00:00Z"
                            }
                        ],
                        "created_at": "2025-10-20T10:00:00Z",
                        "updated_at": "2025-10-21T10:00:00Z"
                    }
                }
            )
        ]
    )
    @action(detail=False, methods=['post'], parser_classes=[parsers.MultiPartParser, parsers.FormParser])
    def create_or_update(self, request):
        """创建或更新车辆信息（包括图片）"""
        # 额外检查：确保当前用户是司机角色
        if request.user.role != User.Role.DRIVER:
            return Response(
                {'error': '只有认证的司机用户才能创建或更新车辆信息'},
                status=status.HTTP_403_FORBIDDEN
            )
            
        license_plate = request.data.get('license_plate')
        
        # 处理行驶证图片上传
        vehicle_license_image = None
        old_vehicle_license_image = None
        
        # 处理车辆图片上传
        vehicle_image = None
        old_vehicle_image = None
        
        # 检查是否已存在该车牌号的车辆（同一用户）
        try:
            existing_vehicle = Vehicle.objects.get(license_plate=license_plate, user=request.user)
            # 保存旧的行驶证图片URL，用于后续删除
            old_vehicle_license_image = existing_vehicle.vehicle_license_image
            # 保存旧的车辆图片URL，用于后续删除
            old_vehicle_image = existing_vehicle.vehicle_image
        except Vehicle.DoesNotExist:
            existing_vehicle = None
            
        if 'vehicle_license_image' in request.FILES:
            try:
                cos_manager = TencentCOSManager()
                image_file = request.FILES['vehicle_license_image']
                file_extension = image_file.name.split('.')[-1] if '.' in image_file.name else 'jpg'
                cos_key = cos_manager.generate_key(request.user.id, 'vehicle_license', file_extension)
                vehicle_license_image = cos_manager.upload_file(image_file, cos_key)
                
                # 如果有旧的行驶证图片，尝试从COS中删除
                if old_vehicle_license_image and vehicle_license_image:
                    try:
                        # 从图片URL中提取COS中的文件key
                        from urllib.parse import urlparse
                        parsed_url = urlparse(old_vehicle_license_image)
                        old_key = parsed_url.path.lstrip('/')  # 移除开头的斜杠
                        
                        # 从COS中删除旧文件
                        cos_manager.delete_file(old_key)
                    except Exception as delete_error:
                        logger.error(f"删除旧行驶证图片失败: {delete_error}")
                        # 即使删除失败，我们仍然继续执行
                        
            except Exception as e:
                return Response(
                    {'error': f'行驶证图片上传失败: {str(e)}'}, 
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR
                )
        elif 'vehicle_license_image' in request.data and request.data['vehicle_license_image']:
            # 如果是URL形式，则直接使用
            vehicle_license_image = request.data['vehicle_license_image']
            
        # 处理车辆图片上传
        if 'vehicle_image' in request.FILES:
            try:
                cos_manager = TencentCOSManager()
                image_file = request.FILES['vehicle_image']
                file_extension = image_file.name.split('.')[-1] if '.' in image_file.name else 'jpg'
                cos_key = cos_manager.generate_key(request.user.id, 'vehicle', file_extension)
                vehicle_image = cos_manager.upload_file(image_file, cos_key)
                
                # 如果有旧的车辆图片，尝试从COS中删除
                if old_vehicle_image and vehicle_image:
                    try:
                        # 从图片URL中提取COS中的文件key
                        from urllib.parse import urlparse
                        parsed_url = urlparse(old_vehicle_image)
                        old_key = parsed_url.path.lstrip('/')  # 移除开头的斜杠
                        
                        # 从COS中删除旧文件
                        cos_manager.delete_file(old_key)
                    except Exception as delete_error:
                        logger.error(f"删除旧车辆图片失败: {delete_error}")
                        # 即使删除失败，我们仍然继续执行
                        
            except Exception as e:
                return Response(
                    {'error': f'车辆图片上传失败: {str(e)}'}, 
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR
                )
        elif 'vehicle_image' in request.data and request.data['vehicle_image']:
            # 如果是URL形式，则直接使用
            vehicle_image = request.data['vehicle_image']
        
        # 检查是否已存在该车牌号的车辆（同一用户）
        try:
            vehicle = Vehicle.objects.get(license_plate=license_plate, user=request.user)
            # 更新现有车辆
            serializer = VehicleUpdateSerializer(vehicle, data=request.data, partial=True)
            serializer.is_valid(raise_exception=True)
            # 如果有新的行驶证图片，则更新
            if vehicle_license_image:
                serializer.validated_data['vehicle_license_image'] = vehicle_license_image
            # 如果有新的车辆图片，则更新
            if vehicle_image:
                serializer.validated_data['vehicle_image'] = vehicle_image
            serializer.save()
            message = "车辆信息更新成功"
            # 重新获取vehicle对象，确保能正确关联图片
            vehicle = Vehicle.objects.get(license_plate=license_plate, user=request.user)
        except Vehicle.DoesNotExist:
            # 创建新车辆
            serializer = VehicleCreateSerializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            # 如果有行驶证图片，则更新
            if vehicle_license_image:
                serializer.validated_data['vehicle_license_image'] = vehicle_license_image
            # 如果有车辆图片，则更新
            if vehicle_image:
                serializer.validated_data['vehicle_image'] = vehicle_image
            serializer.save(user=request.user)
            # 重新获取vehicle对象，确保能正确关联图片
            vehicle = Vehicle.objects.get(license_plate=license_plate, user=request.user)
            message = "车辆信息创建成功"
        
        # 重新获取vehicle对象
        vehicle = Vehicle.objects.get(id=vehicle.id)
        
        return Response({
            'message': message,
            'vehicle': VehicleSerializer(vehicle).data
        })
    
    @extend_schema(
        summary="更改车辆状态",
        description="""更改指定车辆的状态，如空闲、运输中、维护中或不可用。
        
        特殊说明：
        - 当车辆ID为'me'时，更改当前司机用户的第一辆车辆状态
        - is_approved字段表示车辆是否已通过审核，该字段由管理员在审核过程中设置，用户无法直接修改
        """,
        request={
            'application/json': {
                'type': 'object',
                'properties': {
                    'status': {
                        'type': 'string',
                        'enum': ['available', 'in_transit', 'maintenance', 'unavailable'],
                        'description': '车辆状态'
                    }
                },
                'required': ['status']
            }
        },
        responses={
            200: VehicleSerializer
        },
        tags=['Vehicles'],
        examples=[
            OpenApiExample(
                '更改状态请求示例',
                summary='更改状态请求示例',
                description='更改车辆状态的请求参数示例',
                value={
                    "status": "in_transit"
                }
            ),
            OpenApiExample(
                '更改状态响应示例',
                summary='更改状态响应示例',
                description='更改车辆状态成功的响应示例',
                value={
                    "message": "车辆状态更新成功",
                    "vehicle": {
                        "id": 1,
                        "user": {
                            "id": 1,
                            "phone": "13800138000",
                            "role": "driver",
                            "avatar": "https://example.com/avatar.jpg",
                            "company": "ABC运输公司",
                            "credit_score": "4.8"
                        },
                        "license_plate": "粤A12345",
                        "vehicle_type": "tank_truck",
                        "vehicle_type_display": "罐车",
                        "capacity": "20.00",
                        "length": "12.50",
                        "width": "2.50",
                        "height": "3.00",
                        "current_location": "广东省广州市天河区",
                        "longitude": "113.280661",
                        "latitude": "23.125178",
                        "location_updated_at": "2025-10-21T10:00:00Z",
                        "status": "in_transit",
                        "status_display": "运输中",
                        "available_time": "2025-10-25T08:00:00Z",
                        "vehicle_license": "LD123456789012",
                        "vehicle_license_image": "https://example.com/license.jpg",
                        "is_approved": True,
                        "images": [
                            {
                                "id": 1,
                                "image_url": "https://example.com/vehicle_front.jpg",
                                "description": "车辆正面",
                                "image_type": "exterior",
                                "image_type_display": "车辆外观",
                                "created_at": "2025-10-20T10:00:00Z"
                            }
                        ],
                        "created_at": "2025-10-20T10:00:00Z",
                        "updated_at": "2025-10-21T10:00:00Z"
                    }
                }
            )
        ]
    )
    @action(detail=True, methods=['post'])
    def change_status(self, request, pk=None):
        """更改车辆状态"""
        # 处理'me'参数
        if pk == 'me':
            # 检查用户是否已认证
            if not request.user.is_authenticated:
                return Response(
                    {'error': '用户未认证'}, 
                    status=status.HTTP_401_UNAUTHORIZED
                )
            
            # 检查用户是否为司机角色
            if request.user.role != User.Role.DRIVER:
                return Response(
                    {'error': '只有司机用户才能使用此功能'}, 
                    status=status.HTTP_403_FORBIDDEN
                )
            
            # 获取当前司机的第一辆车辆
            try:
                vehicle = Vehicle.objects.filter(user=request.user).first()
                if not vehicle:
                    return Response(
                        {'error': '当前用户没有注册车辆'}, 
                        status=status.HTTP_404_NOT_FOUND
                    )
            except Exception as e:
                return Response(
                    {'error': '获取车辆信息失败'}, 
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR
                )
        else:
            vehicle = self.get_object()
        
        # 检查是否是车辆的所有者
        if vehicle.user != request.user:
            return Response(
                {'error': '只有车辆的所有者才能更改状态'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        new_status = request.data.get('status')
        if not new_status:
            return Response(
                {'error': '缺少状态参数'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # 检查状态是否有效
        if new_status not in dict(Vehicle.Status.choices):
            return Response(
                {'error': '无效的状态值'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # 更新车辆状态
        vehicle.status = new_status
        vehicle.save()
        
        return Response({
            'message': '车辆状态更新成功',
            'vehicle': VehicleSerializer(vehicle).data
        })